<template>
  <div>
    <el-dialog
      :title="`${formData.id ? '修改' : '新建'}用户`"
      :visible="dialogVisible"
      width="46%"
      @close="close"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        :inline="true"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="username" label="管理员名称">
              <el-input
                v-model="formData.username"
                placeholder="请输入用户姓名"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
          ><el-form-item prop="email" label="管理员邮箱">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱"
            /> </el-form-item></el-col>
          <el-col :span="12">
            <el-form-item
              prop="password"
              label="管理员密码"
              :class="{ 'password-required': !formData.id }"
            >
              <el-input
                v-model="formData.password"
                :placeholder="formData.id ? `留空表示不修改` : `请输入密码`"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
          ><el-form-item prop="phone" label="管理员手机">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机"
            /> </el-form-item></el-col>
          <el-col
            :span="12"
          ><el-form-item label="管理员状态">
            <el-switch
              v-model="formData.status"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="2"
            /> </el-form-item></el-col>
          <el-col
            :span="12"
          ><el-form-item label="管理员头像">
            <div class="avatar-wrap">
              <el-image
                v-if="formData.avatar"
                style="width: 80px; height: 80px; margin-right: 20px"
                :src="`http://122.51.249.55:7005/${formData.avatar}`"
              />
              <el-button
                type="success"
                icon="el-icon-upload"
                size="small"
                @click="isCropperimgShow = true"
              >选择
              </el-button>
            </div>
          </el-form-item></el-col>
          <el-col :span="24">
            <el-form-item prop="roleid_list" label="管理员角色">
              <el-checkbox-group v-model="formData.roleid_list">
                <el-checkbox
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.id"
                >{{ item.role_name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <cropperimg :isshow.sync="isCropperimgShow" @upload="uploadAvatar" />
  </div>
</template>

<script>
import {
  addUser,
  editUserData,
  fetchRoleList,
  fetchUserData
} from '@/api/user_c'
import Cropperimg from './Cropperimg'
export default {
  name: 'EditUser',
  components: {
    Cropperimg
  },
  props: {
    dialogVisible: {
      require: true,
      default: false
    }
  },
  data() {
    var validatePass = (rule, value, callback) => {
      // 仅当处于新增状态才会检测是否填写
      if (value === '' && !this.formData.id) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        status: 1,
        avatar: '',
        password: '',
        roleid_list: []
      },
      rules: {
        username: [
          {
            required: true,
            message: '用户名必填',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱必填',
            trigger: 'blur'
          },
          {
            pattern:
              /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/,
            message: '邮箱格式不正确',
            trigger: 'blur'
          }
        ],
        password: [
          {
            validator: validatePass,
            trigger: 'blur'
          },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
            message: '密码必须同时包含字母和数字, 且长度在6-20位之间',
            trigger: 'blur'
          }
        ],

        phone: [
          {
            required: true,
            message: '手机号必填',
            trigger: 'blur'
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur'
          }
        ],
        roleid_list: [
          {
            required: true,
            message: '角色必选',
            trigger: 'blur'
          }
        ]
      },
      roleList: [],
      isCropperimgShow: false
    }
  },
  created() {
    this.loadRoleList()
  },
  methods: {
    close() {
      this.formData = {
        status: 1,
        avatar: '',
        password: '',
        roleid_list: []
      }
      this.$emit('update:dialog-visible', false)
    },
    async submit() {
      await this.$refs.formRef.validate()
      if (this.formData.id) {
        const resp = await editUserData(this.formData)
        if (!resp.success) return this.$message(resp.msg)
        this.$message.success('修改成功')
      } else {
        const resp = await addUser(this.formData)
        if (!resp.success) return this.$message(resp.msg)
        this.$message.success('添加成功')
      }
      this.$emit('update-list')
      this.close()
    },
    uploadAvatar(res) {
      this.formData.avatar = res.data.url
    },
    async loadRoleList() {
      const resp = await fetchRoleList()
      this.roleList = resp.data.list
    },
    async loadUserData(id) {
      const resp = await fetchUserData(id)
      this.formData = resp.data
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 15px 20px 10px !important;
  border-bottom: 1px solid #e9ecef;
}
.avatar-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
::v-deep .password-required .el-form-item__label::before {
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
</style>
